# application/hooks.py

from flask import g, session,request
from .models import User
from .exts import db
import logging
from flask import current_app

# 以下全部是钩子函数，需要在工厂函数__init__.py中注册

def before_request():
    # logging.info("这是一条信息日志")
    # logging.info(f"before_request:url={request.url}")
    g.user = None
    if 'user_id' in session:
        g.user = User.query.get(session['user_id'])

def after_request(response):
    # logging.info(f"after_request:url={request.url}, status={response.status}")
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    return response

def teardown_request(exception=None):
    if exception:
        db.session.rollback()
    db.session.remove()
    
# @app.teardown_appcontext
# def teardown_db(exception):
#     print('-->teardown application')